#include "common_h.h"

u8 chksum_xor8(const u8 *data, u32 num)
{	
	u8 ret = data[0];
		
	for(u16 nr=1; nr<num; nr++){
		ret += data[nr];
	}

	return ret;
}

u8 chksum_add8(const u8 *data, u32 num)
{
	u8 ret = 0;

	while(num--){
		ret += data[num];
	}

	return ret;
}

u16 chksum_add16(u8 *dptr, u16 len)
{
	u16 ret = 0;

	for (; len > 0; len--) {
		ret += *dptr++;
	}

	return ret;
}

u32 chksum_add32(u8 *dptr, u16 len)
{
	u32 ret = 0;

	for (; len > 0; len--) {
		ret += *dptr++;
	}

	return ret;
}

void mem_cpy (void* dst, const void* src, int cnt) 
{
	char *d = (char*)dst;
	const char *s = (const char *)src;
	while (cnt--) *d++ = *s++;
}

/* Fill memory */
void mem_set (void* dst, int val, int cnt) 
{
	char *d = (char*)dst;
	while (cnt--) *d++ = (char)val;
}

/* Compare memory to memory */
int mem_cmp (const void* dst, const void* src, int cnt) 
{
	const char *d = (const char *)dst, *s = (const char *)src;
	int r = 0;
	while (cnt-- && (r = *d++ - *s++) == 0) ;
	return r;
}

 
u8 queue_init(LinkQueue *Q)
{ 
	if((Q->front != NULL)||(Q->rear != NULL)||(Q->item != 0)){
		return 1;
	}
	Q->front=Q->rear= NULL;
	Q->front->next=NULL;
	Q->rear->next = NULL;
	Q->item = 0;
	
	return 0;
}

u16 queue_item(LinkQueue *Q)
{ 
	return (Q->item);
}
 
QElemType queue_get(LinkQueue *Q)
{
	if(Q->item==0){
		return NULL;
	}
	
	return Q->front->data;
}
 
u8 queue_add(LinkQueue *Q,QElemType e)
{ 	
	QueuePtr p=(QNode *)pvPortMalloc(sizeof(QNode));
	
	if(!p)  return 1;
	
	p->data=e;
	p->next=NULL;

	if(Q->item==0){
		Q->front=Q->rear= p;
		Q->front->next=NULL;
	}
	else{
		Q->rear->next=p;
		Q->rear=p;	
	}

	Q->item++;
	
	return 0;
}
 
u8 queue_del(LinkQueue *Q)
{
	QueuePtr p;
	
	if((Q->front==NULL)||(Q->rear==NULL)||(Q->item==0))
		return 1;

	if(Q->item==1){
		p=Q->front;
		vPortFree(p);
		Q->front=Q->rear= NULL;  
		Q->front->next=NULL;
		Q->rear->next = NULL;
		Q->item = 0;
	}
	else{
		p=Q->front;
		Q->front = Q->front->next;
		vPortFree(p);
		Q->item--;
	}

	return 0;
}
 


